<template>
  <div class="base-content">
    <!--部门-->
    <!-- <div v-if="deptreeIsShow" class="department-tree">
      <p class="department-title">组织架构</p>

      <el-tree
        class="customer-tree"
        :data="departmentData"
        default-expand-all
        row-key="id"
        :check-on-click-node="true"
        :props="{ label: 'name', children: 'children' }"
        @node-click="checkDepart"
      />
    </div> -->
    <div class="basic-info">
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryForm"
        :label-width="$i18n.locale === 'en' ? '160px' : '100px'"
      >
        <el-form-item
          v-if="showTableColumn"
          :label="dataList.DeviceNumber"
          prop="num"
        >
          <el-input
            v-model="queryForm.num"
            :placeholder="dataList.DeviceNumber"
          />
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
          prop="name"
        >
          <el-input
            v-model="queryForm.name"
            :placeholder="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          />
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="dataList.DeviceSpecifications"
          prop="specifications"
        >
          <el-input
            v-model="queryForm.specifications"
            :placeholder="dataList.DeviceSpecifications"
          />
        </el-form-item>
        <el-form-item
          v-if="!showTableColumn"
          :label="dataList.Device"
          prop="device"
        >
          <el-input
            v-model="queryForm.device"
            :placeholder="dataList.DeviceClassifyId"
          />
        </el-form-item>
        <el-form-item :label="dataList.DeviceClassifyId" prop="classifyId">
          <div style="width: 200px">
            <DeviceCategory
              v-model="queryForm.classifyId"
              :is-all="true"
            ></DeviceCategory>
          </div>
        </el-form-item>
        <el-form-item :label="dataList.DeviceStatus" prop="statusId">
          <div style="width: 200px">
            <DicDropDownList
              v-model="queryForm.statusId"
              dict-code="deviceStatusList"
              :is-all="true"
              :not-display-text="notDisplayText"
              :display-text.sync="displayText"
            />
          </div>
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="
            $i18n.locale === 'en'
              ? dataList.eDeviceStorageAddress
              : dataList.DeviceStorageAddress
          "
          prop="storageAddress"
        >
          <el-input
            v-model="queryForm.storageAddress"
            :placeholder="
              $i18n.locale === 'en'
                ? dataList.eDeviceStorageAddress
                : dataList.DeviceStorageAddress
            "
          />
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="dataList.DeviceFactoryNum"
          prop="factoryNum"
        >
          <el-input
            v-model="queryForm.factoryNum"
            :placeholder="dataList.DeviceFactoryNum"
          />
        </el-form-item>

        <el-form-item
          v-if="showTableColumn"
          :label="dataList.DevicePersonResponsibleId"
          prop="personResponsibleName"
        >
          <!-- <el-input
            v-model="queryForm.personResponsibleName"
            ::placeholder="dataList.DevicePersonResponsibleId"
          /> -->
          <el-select
            v-model="queryForm.personResponsibleId"
            :placeholder="dataList.EnterDevicePersonResponsibleId"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteGroup"
            :loading="searchUserLoading"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              ::label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="dataList.DeviceUsageState"
          prop="usageState"
        >
          <el-select
            ref="select"
            v-model="queryForm.usageState"
            style="width: 200px"
            :placeholder="dataList.Placeholder"
          >
            <el-option
              v-for="item in usageStateList"
              :key="item.value"
              ::label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="showTableColumn"
          :label="dataList.Optime"
          prop="updateDateArray"
        >
          <el-date-picker
            v-model="queryForm.updateDateArray"
            type="daterange"
            :range-separator="dataList.To"
            :start-placeholder="dataList.StartDate"
            :end-placeholder="dataList.EndDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="base-content-operate">
        <el-button type="primary" @click="onQuery">{{ btn.Query }}</el-button>
        <!-- <el-button type="primary" @click="tiaozhuan">跳转</el-button> -->
        <el-button @click="cancelForm">{{ btn.Reset }}</el-button>
        <el-button
          v-if="showTableColumn"
          icon="el-icon-plus"
          type="primary"
          @click="onNew"
          >{{ btn.Add }}</el-button
        >
        <el-button v-if="showTableColumn" type="primary" @click="batchPrint">{{
          btn.PrintBarcode
        }}</el-button>
        <el-button v-if="showTableColumn" type="primary" @click="tagPrint">{{
          btn.PrintTag
        }}</el-button>
        <el-button
          v-if="buttonHideQrCode"
          type="primary"
          @click="qrCodePrint"
          >{{ btn.PrintQrCode }}</el-button
        >
        <el-button
          v-if="showTableColumn"
          icon="el-icon-download"
          type="primary"
          @click="Export"
          >{{ btn.Export }}</el-button
        >
        <el-button
          v-if="showTableColumn"
          type="primary"
          @click="relevancyParts"
          >{{ btn.JoinAccessory }}</el-button
        >
        <el-button
          icon="el-icon-document-copy"
          type="primary"
          @click="importData()"
          >{{ btn.Import }}</el-button
        >
      </div>

      <el-table
        ref="deviceTagTable"
        :data="list"
        element-loading-text="Loading"
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="multipleSelectState" type="selection" width="55">
        </el-table-column>
        <el-table-column v-if="!multipleSelectState">
          <template slot-scope="scope">
            <el-link type="primary" @click="select(scope.row)">{{
              btn.Select
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceNumber">
          <template slot-scope="scope">
            <el-link type="primary" @click="toView(scope.row)">
              {{ scope.row.num }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
          "
        >
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSpecifications">
          <template slot-scope="scope">
            {{ scope.row.specifications }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceClassifyId">
          <template slot-scope="scope">
            {{ scope.row.classifyName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceSupplierName">
          <template slot-scope="scope">
            {{ scope.row.supplierName }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceFactoryNum">
          <template slot-scope="scope">
            {{ scope.row.factoryNum }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceStatus">
          <template slot-scope="scope">
            <span :style="stateStyle(scope.row)">
              {{ scope.row.statusName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DeviceUseState">
          <template slot-scope="scope">
            <span :style="useStateStyle(scope.row)">
              {{ scope.row.useStateLabel }}
            </span>
          </template>
        </el-table-column>
        <el-table-column v-if="showTableColumn" :label="dataList.DeviceUseDate">
          <template slot-scope="scope">
            {{ formatTime(scope.row.useDate) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="
            $i18n.locale === 'en'
              ? dataList.eDeviceStorageAddress
              : dataList.DeviceStorageAddress
          "
        >
          <template slot-scope="scope">
            {{ scope.row.storageAddress }}
          </template>
        </el-table-column>
        <el-table-column :label="dataList.DevicePersonResponsibleId">
          <template slot-scope="scope">
            {{ scope.row.personResponsibleName }}
          </template>
        </el-table-column>
        <el-table-column v-if="showTableColumn" :label="dataList.OperatorName">
          <template slot-scope="scope">
            {{ scope.row.operatorName }}
          </template>
        </el-table-column>
        <el-table-column v-if="showTableColumn" :label="dataList.Optime">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column>
        <el-table-column v-if="showTableColumn" :label="dataList.Operation">
          <template slot-scope="scope">
            <div class="base-table-operation">
              <el-link
                size="mini"
                type="primary"
                @click="handleEdit(scope.row)"
                >{{ btn.Edit }}</el-link
              >
              <el-link
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
                >{{ btn.Delete }}</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <BasePagination
        :total="pagination.total"
        :current-page="pagination.pageIndex"
        :page-count="pagination.total"
        @changePage="changePage"
        @sizeChange="sizeChange"
      />
    </div>
    <device-add-dialog
      v-if="deviceAddDialogVisible"
      ref="deviceAddDialog"
      :dialog-form-visible.sync="deviceAddDialogVisible"
      :deptree-level="deptreeIsShow"
      @getList="getList"
    ></device-add-dialog>
    <DeviceEditDialog
      v-if="deviceEditDialogVisible"
      ref="deviceEditDialog"
      :dialog-form-visible.sync="deviceEditDialogVisible"
      :edit-id.sync="editId"
      :deptree-level="deptreeIsShow"
      @getList="getList"
    />
    <DeviceViewDialog
      v-if="deviceViewDialogVisible"
      ref="deviceViewDialog"
      :dialog-form-visible.sync="deviceViewDialogVisible"
      :edit-id.sync="editId"
    />
    <device-tag-dialog
      v-if="deviceTagDialogShow"
      ref="deviceTagDialog"
      :dialog-form-visible.sync="deviceTagDialogShow"
    ></device-tag-dialog>
    <PrintBarCode
      v-if="devicePrintDialogVisible"
      :dialog-form-visible.sync="devicePrintDialogVisible"
      :num-list.sync="deviceNumList"
    />
    <DevicePartsDialog
      v-if="devicePartsDialogVisible"
      :dialog-form-visible.sync="devicePartsDialogVisible"
      :device-id-list.sync="deviceId"
    />
    <ImportComponents
      ref="ImportComponents"
      v-model="importVisible"
      @success="closeimportDialog"
      @UploadMethod="UploadMethod"
      @DownloadMethod="DownloadMethod"
    />
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog"
      :title="dataList.TagSetting"
      align="center"
      :visible.sync="dialogFormVisible"
      @closed="closeDialog"
    >
      <div>
        <el-form
          ref="form"
          :rules="formRules"
          :model="form"
          label-width="300px"
        >
          <el-form-item :label="dataList.PaperWidth" prop="paperWidth">
            <el-input v-model="form.paperWidth"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.PaperHeight" prop="paperHeight">
            <el-input v-model="form.paperHeight"></el-input>
          </el-form-item>

          <el-form-item :label="dataList.TopMargin" prop="topMargin">
            <el-input v-model="form.topMargin"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.RightMargin" prop="rightMargin">
            <el-input v-model="form.rightMargin"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.BottomMargin" prop="bottomMargin">
            <el-input v-model="form.bottomMargin"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.LeftMargin" prop="leftMargin">
            <el-input v-model="form.leftMargin"></el-input>
          </el-form-item>

          <el-form-item :label="dataList.FontSize" prop="fontSize">
            <el-input v-model="form.fontSize"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.QrCodeSize" prop="qrCodeSize">
            <el-input v-model="form.qrCodeSize"></el-input>
          </el-form-item>
          <el-form-item :label="dataList.TagSize" prop="tagSize">
            <el-input v-model="form.tagSize"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="primary" @click="onSubmit">{{
            btn.Confirm
          }}</el-button>
          <el-button @click="closeDialog">{{ btn.Cancel }}</el-button>
        </div>

        <!-- style="display: none" -->
        <div id="printDiv" ref="printDiv" style="display: none">
          <div v-for="(items, index) in dataTables" :key="index">
            <div class="contentData">
              <div style="font-size: 40%">
                <div id="message">
                  <span style="font-weight: bold"
                    >{{ dataList.DeviceName }}:{{ items.name }}</span
                  >
                  <br />
                  <span>{{ dataList.DeviceNumber }}：{{ items.num }}</span>
                  <br />
                  <span
                    >{{ dataList.DeviceSpecifications }}：{{
                      items.specifications
                    }}</span
                  >
                  <br />
                  <span
                    >{{ dataList.DevicePersonResponsibleId }}：{{
                      items.personResponsibleName
                    }}</span
                  >
                  <br />
                  <span>{{ dataList.Phone }}：{{ items.phone }}</span>
                </div>
                <div style="width: 30%; float: left; margin-top: -2%">
                  <img
                    v-if="!hideQrCode"
                    id="QRCode"
                    :src="items.qRCodeNumUrl"
                  />
                  <img
                    v-if="hideQrCode"
                    style="width: 95%"
                    :src="items.qrCodeData"
                  />
                </div>
              </div>
              <hr
                style="
                  border-top: 1px solid blue;
                  float: left;
                  width: 100%;
                  margin-top: 0%;
                "
              />
              <div style="float: left; width: 100%" class="image-container">
                <img
                  v-for="(item, i) in items.deviceTagInfoDtoList"
                  :key="i"
                  class="TagImg"
                  :src="item.url"
                />
              </div>
            </div>
          </div>
        </div>
        <iframe
          ref="printIframe"
          frameborder="0"
          scrolling="no"
          style="margin: 0px; padding: 0px; width: 0px; height: 0px"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserListNoPage } from "../../api/PermissionUser.js";
import DeviceAddDialog from "./DeviceAddDialog.vue";
import DeviceEditDialog from "./DeviceEditDialog.vue";
import DeviceViewDialog from "./DeviceViewDialog.vue";
import DevicePartsDialog from "./DevicePartsDialog.vue";
import DeviceCategory from "../../components/DeviceCategory.vue";
import DicDropDownList from "../../components/DicDropDownList.vue";
import {
  getList,
  deleteRecord,
  getDepartTree,
  DeviceLabelSettingGet,
  DeviceLabelSettingUpdate,
  ImportDeviceUrl,
  DownloadDeviceTemplate,
} from "../../api/Device";
import PrintBarCode from "../../components/PrintBarCode.vue";
import { export_json_to_excel } from "@/vendor/Export2Excel";
import QRCode from "qrcode";
import { mapGetters } from "vuex";
import { formatTimeMin, formatTimeMax, formatTime } from "../../utils/time";
import { GetStaticImgInfo, GetStaticFileInfo } from "@/api/Base";
import { getList as getDictList, getConfigByKey } from "../../api/SystemDict";

export default {
  name: "DeviceTable",
  components: {
    DeviceAddDialog,
    DeviceEditDialog,
    DeviceViewDialog,
    DevicePartsDialog,
    DicDropDownList,
    DeviceCategory,
    PrintBarCode,
  },
  props: {
    displayText: {
      type: Array,
      default: () => [],
    },
    notDisplayText: {
      type: Array,
      default: () => [],
    },
    queryFormParent: {
      type: Object,
      default: () => {},
    },
    multipleSelectState: {
      type: Boolean, // 布尔
      default: true, // 必填
    },
    // 弹窗传参
    showTableColumn: {
      type: Boolean, // 布尔
      default: true, // 必填
    },
    statusId: {
      type: Number, // 数字
      default: -1, // 必填
    },
    // 被选中的行
    checkedRows: {
      type: Array, // 被选中的行
      default: () => [], // 被选中的行
    },
    deviceIdList: {
      type: Array, // 筛选的设备ID
      default: () => [], // 被选中的行
    },
  },

  data() {
    return {
      usageStateList: [
        {
          value: null,
          name: "全部",
        },
        {
          value: "0",
          name: "空闲",
        },
        {
          value: "1",
          name: "使用中",
        },
      ],
      // tHeader: [
      //   "设备编号",
      //   "设备名称",
      //   "型号规格",
      //   "设备分类",
      //   "供应商",
      //   "出厂编号",
      //   "设备状态",
      //   "投用日期",
      //   "存放地点",
      //   "责任人",
      //   "操作人",
      //   "操作时间",
      // ],
      filterVal: [
        "num",
        "name",
        "specifications",
        "classifyName",
        "supplierName",
        "factoryNum",
        "statusName",
        "useDate",
        "storageAddress",
        "personResponsibleName",
        "operatorName",
        "updateTime",
      ],
      formRules: {
        fontSize: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        qrCodeSize: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        tagSize: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        paperWidth: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        paperHeight: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        topMargin: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        rightMargin: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        bottomMargin: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        leftMargin: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      hideQrCode: false,
      buttonHideQrCode: false,
      importVisible: false,
      form: {
        fontSize: "",
        qrCodeSize: "",
        tagSize: "",
        paperWidth: "",
        paperHeight: "",
        topMargin: "",
        rightMargin: "",
        bottomMargin: "",
        leftMargin: "",
      },
      QRImgUrl: "",
      loading: false,
      editId: "",
      deviceId: [],
      dataTables: [],
      checkedRowsList: [],
      dialogFormVisible: false,
      devicePartsDialogVisible: false,
      devicePrintDialogVisible: false,
      deviceAddDialogVisible: false,
      deviceEditDialogVisible: false,
      deviceViewDialogVisible: false,
      deviceTagDialogShow: false,
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      list: [],
      userList: [],
      searchUserLoading: false,
      deviceNumList: [],
      queryForm: {
        urlConditionString: "",
        device: "",
        personResponsibleName: "",
        personResponsibleId: "",
        num: "",
        name: "",
        specifications: "",
        classifyId: "-1",
        statusId: "-1",
        storageAddress: "",
        factoryNum: "",
        // personResponsibleId: 0,
        updateDateArray: [],
        startTime: null,
        endTime: null,
        departId: "0",
        usageState: null,
      },
      classifyList: [],
      departmentData: [],
      pageLoading: false,
      deptreeIsShow: false,
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },

  created() {
    if (this.$i18n.locale === "en") {
      this.usageStateList.forEach((item, index) => {
        item.name = [
          this.$i18n.t("ModuleDevice.components.all"),
          this.$i18n.t("ModuleDevice.components.idle"),
          this.dataList.Usaging,
        ][index];
      });
    }

    this.checkedRowsList = this.checkedRows;
    this.initData();
    this.getList();
  },
  methods: {
    // 关联配件
    relevancyParts() {
      if (this.dataTables == null || this.dataTables.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Device.PleaseSelectData"));
        return false;
      }
      this.deviceId = this.dataTables.map((x) => x.id);
      this.devicePartsDialogVisible = true;
    },
    // 选择
    select(row) {
      this.$emit("confirmSelected", row);
    },
    async initData() {
      await getDictList({ dictCode: "DevicePermission" }).then((res) => {
        var data = res.data.dataList;
        if (data && data[0].value === "1") {
          this.deptreeIsShow = true;
          this.getDepartmentTree();
        }
      });
      var qrCodeValue = await this.getQrcodeIsEnabel();

      if (qrCodeValue && qrCodeValue === "1") {
        this.buttonHideQrCode = true;
      }
    },
    formatTime,
    // tiaozhuan() {
    //   const _this = this;
    //   // 浏览器打开新标签
    //   const routeUrl = this.$router.resolve({
    //     path: "/DeviceViewH5",
    //     query: {
    //       id: this.list[0].id,
    //     },
    //   });
    //   window.open(routeUrl.href, "_blank");
    // },
    export_json_to_excel,
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
    // 获取部门树
    getDepartmentTree() {
      getDepartTree()
        .then((res) => {
          this.departmentData = res.data;
          this.pageLoading = false;
          if (res.data.length) {
            // this.checkDepart(this.departmentData[0]);
          }
        })
        .catch(() => {
          this.pageLoading = false;
        });
    },
    // 选择部门
    checkDepart(node) {
      this.pagination.pageIndex = 1;
      this.queryForm.departId = node.id;
      this.getList();
    },
    Export() {
      getList(this.queryForm, { pageIndex: 1, pageSize: 10000 }).then((res) => {
        for (var i = 0; i < res.data.dataList.length; i++) {
          res.data.dataList[i].useDate = this.formatTime(
            res.data.dataList[i].useDate
          );
        }
        var data = this.formatJson(this.filterVal, res.data.dataList);
        const tHeader = [
          this.dataList.DeviceNumber,
          this.dataList.DeviceName,
          this.dataList.DeviceSpecifications,
          this.dataList.DeviceClassifyId,
          this.dataList.DeviceSupplierName,
          this.dataList.DeviceFactoryNum,
          this.dataList.DeviceStatus,
          this.dataList.DeviceUseDate,
          this.dataList.DeviceStorageAddress,
          this.dataList.DevicePersonResponsibleId,
          this.dataList.OperatorName,
          this.dataList.Optime,
        ];
        export_json_to_excel({
          header: tHeader, // 表头
          data, // 数据
          filename: this.$t("ModuleDevice.Device.DeviceList"), // "设备列表", // 导出文件名
          autoWidth: true, // 导出宽度自动
          bookType: "xlsx", // 导出后缀
        });
      });
    },
    closeDialog() {
      this.form.fontSize = "";
      this.form.qrCodeSize = "";
      this.form.tagSize = "";
      this.form.paperWidth = "";
      this.form.paperHeight = "";

      this.form.topMargin = "";
      this.form.rightMargin = "";
      this.form.bottomMargin = "";
      this.form.leftMargin = "";

      this.dialogFormVisible = false;
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.printTag();

          DeviceLabelSettingUpdate(this.form).then((res) => {});
        }
      });
    },
    // // 拼接图片地址
    // imgUrl(url) {
    //   // var res = `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${url}`;
    //   var res = `${url}`;
    //   return res;
    // },
    createQrcode(num) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement("canvas");
        QRCode.toDataURL(canvas, num, (err, url) => {
          if (err) {
            reject(err);
          } else {
            resolve(url);
          }
        });
      });
    },
    // 标签打印
    printTag() {
      var printIframe = this.$refs.printIframe;
      var html = this.$refs.printDiv.innerHTML;
      var self = this; // 存储组件实例
      printIframe.setAttribute("srcdoc", html);
      printIframe.onload = function() {
        var style = printIframe.contentWindow.document.createElement("style");
        style.innerHTML = `@page {
          size: ${self.form.paperWidth}mm ${self.form.paperHeight}mm;
          margin: ${self.form.topMargin}mm ${self.form.rightMargin}mm ${self.form.bottomMargin}mm ${self.form.leftMargin}mm; /* 设置上下左右边距为 5 毫米 */
        }
        #QRCode {
          width: ${self.form.qrCodeSize}px;
        }
        .contentData{
          page-break-after: always;
        }
        .image-container {
          display: flex; /* 将容器设置为 flexbox 布局 */
          flex-wrap: nowrap; /* 允许图片换行 */
        }
        #message{
          width: 68%;
          float: left;
          font-size:${self.form.fontSize}px;
        }
        .TagImg{
          width: 100%;
          height: auto;
          max-width: ${self.form.tagSize}px;
          max-height: ${self.form.tagSize}px;
          min-width: ${self.form.tagSize}px;
          min-height: ${self.form.tagSize}px;
          object-fit: contain;
          flex: 1 1 auto;
        }`;

        printIframe.contentWindow.document.head.appendChild(style);

        // 去掉iframe里面的dom的body的padding margin的默认数值
        printIframe.contentWindow.document.body.style.padding = "0px";
        printIframe.contentWindow.document.body.style.margin = "0px";
        // 开始打印
        printIframe.contentWindow.focus();
        printIframe.contentWindow.print();
      };
    },
    // 打印标签
    tagPrint() {
      this.hideQrCode = false;
      if (this.dataTables == null || this.dataTables.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Device.PleaseSelectData"));
        return false;
      }

      for (let i = 0; i < this.dataTables.length; i++) {
        for (
          let o = 0;
          o < this.dataTables[i].deviceTagInfoDtoList.length;
          o++
        ) {
          GetStaticImgInfo(
            this.dataTables[i].deviceTagInfoDtoList[o].imgUrl
          ).then((res) => {
            this.dataTables[i].deviceTagInfoDtoList[o].url = res.data;
            this.$forceUpdate();
          });
        }
      }

      DeviceLabelSettingGet({ type: 2 }).then((res) => {
        this.form = res.data;
      });

      this.dialogFormVisible = true;
      // this.printTag();
    },
    qrCodePrint() {
      if (this.dataTables == null || this.dataTables.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Device.PleaseSelectData"));
        return false;
      }
      this.hideQrCode = true;
      for (let i = 0; i < this.dataTables.length; i++) {
        GetStaticImgInfo(this.dataTables[i].qrCode).then((res) => {
          this.$set(this.dataTables[i], "qrCodeData", res.data);
          this.$forceUpdate();
        });
        for (
          let o = 0;
          o < this.dataTables[i].deviceTagInfoDtoList.length;
          o++
        ) {
          GetStaticImgInfo(
            this.dataTables[i].deviceTagInfoDtoList[o].imgUrl
          ).then((res) => {
            this.dataTables[i].deviceTagInfoDtoList[o].url = res.data;
            this.$forceUpdate();
          });
        }
      }
      DeviceLabelSettingGet().then((res) => {
        this.form = res.data;
      });
      this.dialogFormVisible = true;
    },
    batchPrint() {
      if (this.dataTables == null || this.dataTables.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Device.PleaseSelectData"));
        return false;
      }
      this.deviceNumList = [];
      var data = [];
      for (let i = 0; i < this.dataTables.length; i++) {
        data.push(this.dataTables[i].num);
      }
      this.deviceNumList = data;
      this.devicePrintDialogVisible = true;
    },
    useStateStyle(row) {
      if (row.usageState === 0) {
        return "color:green;font-weight: bold;";
      } else if (row.usageState === 1) {
        return "color:orange;font-weight: bold;";
      }
    },
    stateStyle(row) {
      if (row.statusValue === 10 || row.statusValue === 30) {
        return "color:green;font-weight: bold;";
      } else if (row.statusValue === 40) {
        return "color:orange;font-weight: bold;";
      } else {
        return "color:red;font-weight: bold;";
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm(
        this.$t("ModuleDevice.Message.DeleteMessage"),
        this.$t("ModuleDevice.buttons.Tips"),
        {
          confirmButtonText: this.$t("ModuleDevice.buttons.Confirm"),
          cancelButtonText: this.$t("ModuleDevice.buttons.Cancel"),
          type: "warning",
          center: true,
        }
      )
        .then(() => {
          deleteRecord({ id: row.id })
            .then((res) => {
              this.getList();
            })
            .catch((res) => {});
        })
        .catch((action) => {});
    },
    toView(row) {
      this.editId = row.id;
      this.deviceViewDialogVisible = true;
    },
    changePage(val) {
      this.pagination.pageIndex = val;
      this.getList();
    },
    sizeChange(val) {
      this.pagination.pageIndex = 1;
      this.pagination.pageSize = val;
      this.getList();
    },
    cancelForm() {
      this.$refs.queryForm.resetFields();
      this.queryForm.startDate = null;
      this.queryForm.endDate = null;
      this.pagination.pageIndex = 1;
      this.getList();
    },
    // 下载
    DownloadMethod() {
      DownloadDeviceTemplate().then((res) => {
        if (res.code === 200) {
          GetStaticFileInfo(res.data);
          // const link = document.createElement("a");
          // link.style.display = "none"; // 去除a标签的样式
          // // 设置连接
          // link.href = `${this.$baseProtocol}//${res.data}`;
          // document.body.appendChild(link);
          // 模拟点击事件;
          // link.click();
        } else {
          this.$message.error(this.$t("ModuleDevice.Message.TemplateNoFound"));
        }
      });
    },
    // 上传
    UploadMethod(formData, fileCount) {
      ImportDeviceUrl(formData).then((res) => {
        if (res.code === 200) {
          this.importVisible = false;
          this.$message.success(this.$t("ModuleDevice.Message.ImportSucess"));
          this.getList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    // 导入
    importData() {
      this.importVisible = true;
    },
    // 关闭弹框清空id
    closeimportDialog() {
      this.importVisible = false;
      this.$message.success(this.$t("ModuleDevice.Message.ImportSucess"));
      this.getList();
    },
    getList() {
      if (this.queryFormParent !== undefined && this.queryFormParent !== null) {
        this.queryForm = this.queryFormParent;
      }
      if (this.displayText !== null && this.displayText.length > 0) {
        this.queryForm.statusNameList = "";
        this.displayText.map((item, index) => {
          if (index === 0) {
            this.queryForm.statusNameList += "?statusNameList=" + item;
          } else {
            this.queryForm.statusNameList += "&statusNameList=" + item;
          }
        });
      }
      if (this.notDisplayText !== null && this.notDisplayText.length > 0) {
        this.queryForm.notStatusNameList = "";
        this.notDisplayText.map((item, index) => {
          if (index === 0) {
            this.queryForm.notStatusNameList += "?notStatusNameList=" + item;
          } else {
            this.queryForm.notStatusNameList += "&notStatusNameList=" + item;
          }
        });
      }
      if (this.deviceIdList !== null && this.deviceIdList.length > 0) {
        this.queryForm.idList = "";
        this.deviceIdList.map((item, index) => {
          this.queryForm.idList += "&idList=" + item;
        });
      }
      this.queryForm.departId = sessionStorage.getItem("currentDepartmentId");
      getList(this.queryForm, this.pagination).then((res) => {
        this.list = res.data.dataList;
        this.pagination.total = res.data.total;

        this.$nextTick(() => {
          for (var i = 0; i < this.checkedRowsList.length; i++) {
            this.list.forEach((item) => {
              if (item.id === this.checkedRowsList[i].id) {
                this.$refs.deviceTagTable.toggleRowSelection(item, true);
              }
            });
          }
        });
      });
    },
    onQuery() {
      debugger;
      this.pagination.pageIndex = 1;
      if (this.queryForm.updateDateArray !== undefined) {
        this.queryForm.startDate = formatTimeMin(
          this.queryForm.updateDateArray[0]
            ? this.queryForm.updateDateArray[0]
            : null
        );
        this.queryForm.endDate = formatTimeMax(
          this.queryForm.updateDateArray[1]
            ? this.queryForm.updateDateArray[1]
            : null
        );
      }

      this.getList();
    },
    onNew() {
      this.deviceAddDialogVisible = true;
    },
    handleEdit(row) {
      this.editId = row.id;
      this.deviceEditDialogVisible = true;
    },

    async handleSelectionChange(val) {
      this.dataTables = val;
      for (let i = 0; i < this.dataTables.length; i++) {
        try {
          // 浏览器打开新标签
          const routeUrl = this.$router.resolve({
            path: "/DeviceViewH5",
            query: {
              id: this.dataTables[0].id,
            },
          });
          const href = window.location.href;
          const qrcodeText = routeUrl.href;
          var arr = href.split("#");
          var text = arr[0] + qrcodeText;
          const url = await this.createQrcode(text);
          // const url = await this.createQrcode(this.dataTables[i].num);
          this.$set(this.dataTables[i], "qRCodeNumUrl", url);
        } catch (err) {
          console.log("二维码生成错误：" + err);
        }
      }
    },
    getQrcodeIsEnabel() {
      return new Promise((resolve) => {
        getConfigByKey("QrCode", 0).then((res) => {
          resolve(res.data ? res.data[0].value : "0");
        });
      });
    },
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name: name }).then((res) => {
          resolve(res.data);
        });
      });
    },
    // 搜索人员
    async remoteGroup(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.length) {
        this.userList = filter;
      }
      this.searchUserLoading = false;
    },
  },
};
</script>
<style lang="scss">
.base-content {
  .department-tree {
    width: 240px;
    height: 100%;
    overflow: auto;
    .el-tree {
      height: calc(100% - 64px);
      overflow: auto;
    }
    .department-title {
      width: 100%;
      font-size: 16px;
      font-weight: bold;
      color: #666666;
      padding: 20px;
      box-sizing: border-box;
    }
  }
  .customer-tree {
    background: #f8fbff;
    .el-tree-node__content {
      height: 40px;
      line-height: 40px;
      &:hover {
        color: #4787ff;
        background: rgba(47, 113, 245, 0.2);
      }
      .el-tree-node__label {
        font-size: 12px;
      }
      .el-tree-node__expand-icon {
        font-size: 16px;
        font-weight: bold;
        color: #999;
      }
      .is-leaf {
        color: transparent;
      }
    }
    .is-current {
      & > .el-tree-node__content {
        .el-tree-node__label {
          color: #409eff;
          font-weight: 600;
        }
        .el-tree-node__expand-icon {
          color: #409eff;
        }
        .is-leaf {
          color: transparent;
        }
      }
    }
  }
}
</style>
